package com.haoma.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * jwt工具生成token防伪作用可以存储用户信息
 */
public class JwtHelper {

    private static long tokenExpiration = 60 * 60 * 1000;
    private static String tokenSignKey = "blog";

    public static String createToken(Long userId) {
        String token = Jwts.builder()
                .setSubject("blog-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer) claims.get("userId");
        return userId.longValue();
        // return 1L;
    }




    public static void main(String[] args) {
        String token = JwtHelper.createToken(7L);
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
    }
}